﻿using System;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;

namespace MoneyBook.Controls {
    public static class ImplicitDataTemplateFinder {

        public static DataTemplate FindImplicitDataTemplate(this FrameworkElement source, Type targetType) {
            if (source == null) {
                throw new ArgumentNullException("source");
            }

            DependencyObject target = source;
            while (target != null) {
                if (target is FrameworkElement) {
                    FrameworkElement element = (FrameworkElement)target;
                    DataTemplate result = FindFromResource(element.Resources, targetType);
                    if (result != null) {
                        return result;
                    }
                }
                //TODO: ホンマはXAML上の親を取りたい
                target = VisualTreeHelper.GetParent(target) as DependencyObject;
            }
            
            return FindFromResource(Application.Current.Resources, targetType);
        }

        private static DataTemplate FindFromResource(ResourceDictionary resources, Type targetType) {
            foreach (var value in resources.Values) {
                if (!(value is DataTemplate)) {
                    continue;
                }
                DataTemplate template = (DataTemplate)value;
                if (template.DataType == targetType) {
                    return template;
                }
            }
            return null;
        }
    }

}
